package org.example.spring.service.userServiceImpl;

import org.example.spring.context.BaseContext;
import org.example.spring.domain.dto.CartDTO;
import org.example.spring.mapper.CartMapper;
import org.example.spring.mapper.FlowerMapper;
import org.example.spring.domain.pojo.Cart;
import org.example.spring.domain.pojo.Flower;
import org.example.spring.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private FlowerMapper flowerMapper;


    @Override
    public void addCart(Cart cart) {
        Integer flowerId= cart.getFlowerId();
        Integer count = cartMapper.getFlowerCount(flowerId);
        cart.setUserId(BaseContext.getCurrentId());
        if(count == null) {
            cartMapper.addCart(cart);
        } else {
            cart.setQuantity(count + cart.getQuantity());
            cartMapper.updateCart(cart);
        }
    }

    @Override
    public ArrayList<CartDTO> getCartList() {
        ArrayList<Cart>carts = cartMapper.getCartListByUserId(BaseContext.getCurrentId());
        ArrayList<CartDTO> cartDTOs = new ArrayList<>();
        for(Cart cart: carts) {
            CartDTO cd= new CartDTO();
            cd.setQuantity(cart.getQuantity());
            Flower flower = flowerMapper.getFlowerById(cart.getFlowerId());
            cd.setName(flower.getName());
            cd.setPrice(flower.getPrice());
            cd.setImageUrl(flower.getImageUrl());
            cd.setFlowerId(cart.getFlowerId());
            cartDTOs.add(cd);
        }
        return cartDTOs;
    }

    @Override
    public void deleteCart(Integer flowerId, Integer userId) {
        cartMapper.deleteCart(flowerId, userId);
    }

    @Override
    public void addCart(Integer userId, Integer flowerId, Integer quantity) {
        cartMapper.updateCart(new Cart(userId, flowerId, quantity));
    }
}
